package cn.casc.tools.maven;

import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;

import javax.swing.*;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author max
 * @version 1.0.1
 * @className MyFileItem
 * @description
 * @copyright Copyright (c) 2023
 * @company 天纲梦工厂
 * @datetime 2024/7/18 13:55
 **/

public class FileItem {
    File file;
    String name;
    public FileItem(File file, String name) {
        this.file = file;
        this.name = name;
    }

    public static FileItem[] unzip(File file) {
        try {
            ZipFile zipFile = new ZipFile(file);
            List headerList = zipFile.getFileHeaders();
            List<FileItem> result = new ArrayList<>(headerList.size());
            for (Object item : headerList) {
                FileHeader fileHeader = (FileHeader) item;
                if (!fileHeader.isDirectory()) {
                    result.add(new FileItem(file, fileHeader.getFileName()));
                }
            }
            return result.toArray(result.toArray(new FileItem[0]));
        } catch (Exception e) {
            JOptionPane.showConfirmDialog(null, "zip文件错误", "错误提示", JOptionPane.CLOSED_OPTION);
        }
        return new FileItem[0];
    }

    public static FileItem[] getFileItemArray(String dir) {
        if(dir == null) {
            dir = "";
        }
        File file = new File(dir);
        if(!file.exists()) {
            return new FileItem[0];
        }
        if(file.isFile()) {
            file = file.getParentFile();
        }
        File[] subs = file.listFiles();
        FileItem[] fileItems = new FileItem[subs.length];
        int cnt = -1;
        for(File item:file.listFiles()) {
            fileItems[++cnt] = new FileItem(item, item.getName());
        }
        return fileItems;
    }

    @Override
    public String toString() {
        return this.name;
    }
}